package top.haijunit.work.controller.system;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import top.haijunit.work.core.auth.JwtTokenUtils;
import top.haijunit.work.core.auth.LoginUser;
import top.haijunit.work.core.doamin.Constant;
import top.haijunit.work.core.doamin.Result;
import top.haijunit.work.core.redis.RedissonUtils;

import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;
import java.util.Map;

/**
 * 认证请求控制器
 *
 * @author zhanghaijun
 * @since 2024-09-11
 */
@Slf4j
@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Tag(name = "登录认证")
public class AuthorizationController {

    @Operation(summary = "获取验证码")
    @GetMapping("/captcha")
    public Result<Map<Object, Object>> captcha() {
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(100, 30, 4, 20);
        lineCaptcha.setGenerator(new RandomGenerator("0123456789", 4));
        // 生成验证码uuid
        String uuid = IdUtil.fastSimpleUUID();
        String code = lineCaptcha.getCode();
        String images = "data:image/jpeg;base64," + lineCaptcha.getImageBase64();
        // 验证码存入redis
        RedissonUtils.setCacheObject(String.format(Constant.REDIS_CAPTCHA, uuid), code, Duration.of(60, ChronoUnit.SECONDS));
        // 返回验证码图片
        return Result.success(MapUtil.builder().put("captchaId", uuid).put("image", images).build());
    }

    @Operation(summary = "登录")
    @PostMapping("/login")
    public Result<Object> login(@RequestBody @Validated LoginUser user) {
        if ("zhanghaijun".equals(user.getUsername()) && "123456".equals(user.getPassword())) {
            HashMap<Object, Object> hashMap = new HashMap<>();
            hashMap.put("token", JwtTokenUtils.generateToken(new HashMap<>(), "zhanghaijun"));
            hashMap.put("username", "zhanggaijun");
            return Result.success(hashMap);
        }
        return Result.failed("账号或密码错误!");
    }
}
